package com.mxpio.erp.oa.service.impl;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.oa.entity.SignatureApplication;
import com.mxpio.erp.common.oa.service.SignatureApplicationService;
import com.mxpioframework.camunda.service.BpmnFlowService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
public class SignatureApplicationServiceImpl extends BaseServiceImpl<SignatureApplication> implements SignatureApplicationService {

    @Autowired
    private BpmnFlowService bpmnFlowService;

    @Override
    @Transactional
    public Result<?> submit(String key, String loginUsername, String businessKey, Map<String, Object> properties) {
        String bizNo = properties.get("bizNo").toString();
        SignatureApplication application = this.getById(SignatureApplication.class, bizNo);
        if (application == null){
            return Result.error("单据不存在");
        }
        if (application.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())){
            return Result.error("单据正在审核中，请勿重复提交");
        }
        application.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode());
        this.update(application);

        //发起工作流
        ProcessInstance processInstance = bpmnFlowService.startWithFormByKey(key, loginUsername, businessKey, properties);
        application.setProcessInstanceId(processInstance.getId());
        this.update(application);
        return Result.OK(application);
    }

    @Override
    @Transactional
    public Result<?> submitOK(SignatureApplication reimbursement) {
        String bizNo = reimbursement.getBizNo();
        SignatureApplication application = this.getById(SignatureApplication.class, bizNo);
        if (application == null){
            return Result.error("单据不存在");
        }
        //撤销
        if(StringUtils.equals(reimbursement.getRevoke(),"1")){
            application.setBpmnStatus(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode());
            this.update(application);
            return Result.OK(application);
        }
        //审核通过
        if (reimbursement.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())){
            application.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
        }
        //审核不通过
        if (reimbursement.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CLOSED.getStatusCode())){
            application.setBpmnStatus(OrderStatusEnums.BpmnStatus.CLOSED.getStatusCode());
        }
        this.update(application);
        return Result.OK(application);
    }
}
